package android.tusnotas.util.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import java.security.KeyStore;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.util.ByteArrayBuffer;

import android.tusnotas.connector.MySSLSocketFactory;

public class DownloadFile {
	private String savingPath;
	
	public DownloadFile(String savingPString){
		this.savingPath = savingPString;
		boolean res = (new File(this.savingPath)).mkdir();
		File root = new File("/sdcard");
		String [] files = root.list();
		for(String f : files){
			File i = new File(f);
			System.out.println("path:"+ i.getAbsolutePath() + "permiso:"+i.canWrite());
		}
			
		this.savingPath = savingPString;
	}
	
	public static boolean createSavingPath(String savingPath){
		boolean res = (new File(savingPath)).mkdir();
		return res;
	}
	
	 public void DownloadFromUrl(String fileURL, String fileName) {
		URL url = null;
		try {
			url = new URL(fileURL);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		
		File file = new File(savingPath + "/" + fileName);
		
		
		// Install the all-trusting trust manager
		
//		    SSLContext sc = SSLContext.getInstance("SSL");
//		    sc.init(null, trustAllCerts, new java.security.SecureRandom());
//		    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		try{
			
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			trustStore.load(null, null);
			SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
			HttpsURLConnection.setDefaultSSLSocketFactory(((MySSLSocketFactory)sf).getSslContext().getSocketFactory());
			
			//sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			
			/* Open a connection to that URL. */
			URLConnection ucon = url.openConnection();
			
			/* Define InputStreams to read from the URLConnection. */
			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			
			/* Read bytes to the Buffer until there is nothing more to read(-1). */
			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}
			
			/* Convert the Bytes read to a String. */
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.close();
			
		}catch(IOException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
	 }
	 
	 public static String encodeUrl(String url)
		{
	        if (url!=null) 
	        {
	            StringBuffer tmp = new StringBuffer();
	            int i=0;
	            try 
	            {
	                while (true) 
	                {
	                    int b = (int)url.charAt(i++);
	                    if ((b>=0x30 && b<=0x39) || (b>=0x41 && b<=0x5A) || (b>=0x61 && b<=0x7A) ||(b == 0x2F) || (b == 0x3A) || (b == 0x2D )|| (b == 0x2E)|| (b == 0x2C)|| (b == 0x3F)|| (b == 0x3D) ||(b == 0x26) || (b == 0x5F) || (b == 0x2A)) 
	                    {
	                        tmp.append((char)b);
	                    }
	                    else {
	                        tmp.append("%");
	                        if (b <= 0xf) tmp.append("0");
	                        tmp.append(Integer.toHexString(b));
	                    }
	                }
	            }
	            catch (Exception e) {}
	            return tmp.toString();
	        }
	        return null;
		}    
}
